"""
使用asyncio的异步网络连接来获取sina、sohu的网站首页。

协程小结：
    1.asyncio提供了完善的异步IO支持。
    2.异步操作需要在coroutine中通过yield from完成。
    3.多个coroutine可以封装成一组Task然后并发执行。

"""

import asyncio


@asyncio.coroutine
def wget(host):
    print("wget {host}...".format(host=host))
    connect = asyncio.open_connection(host=host, port=80)
    reader, writer = yield from connect
    header = "GET / HTTP/1.0\r\nHost: {host}%s\r\n\r\n".format(host=host)
    writer.write(header.encode("utf-8"))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b'\r\n' or line == b'':
            break
        print("{host} header > {content}".format(host=host, content=line.decode('utf-8').rstrip()))
    writer.close()


def run():
    # 获取消息循环
    loop = asyncio.get_event_loop()
    tasks = [wget(host) for host in ("www.sina.com.cn", "www.sohu.com")]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()


if __name__ == "__main__":
    run()
